import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElDialog, ElButton, ElForm, ElFormItem, ElMessage, ElSelect, ElOption } from 'element-plus'

import type { FormInstance, FormRules } from 'element-plus'
import type { InfoValuesType, groupType } from './typings'

import styles from '../../index.module.scss'

export default defineComponent({
  props: ['cancel', 'lampPostId'],
  emits: ['submitForm'],
  setup(props, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive<InfoValuesType>({})

    const rules = reactive<FormRules>({
      name: [{ required: true, message: '分组名称不能为空', trigger: 'blur' }]
    })

    const state = reactive({
      groupList: []
    })
    //  提交
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const params = { ...ruleForm }
          const { code } = await store.dispatch('singleLamp/UpdateGroup', {
            lampPostId: props.lampPostId,
            groupId: params.groupId
          })
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            emit('submitForm')
            props.cancel()
          }
        }
      })
    }
    //  取消
    const resetForm = () => {
      ruleFormRef.value?.resetFields()
      props.cancel()
    }

    onMounted(async () => {
      const { data } = await store.dispatch('singleLamp/GroupData')
      state.groupList = data
    })
    return () => (
      <ElDialog
        title="修改分组"
        modelValue={true}
        beforeClose={props.cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={600}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm
          ref={ruleFormRef}
          model={ruleForm}
          rules={rules}
          label-width="140px"
          labelPosition="right"
        >
          <ElFormItem label="分组名称" prop="groupId">
            <ElSelect
              v-model={ruleForm.groupId}
              clearable
              placeholder="分组名称"
              class={styles['model-input']}
            >
              {state.groupList?.map((item: groupType) => (
                <ElOption key={item?.id} label={item?.name} value={item?.id} />
              ))}
            </ElSelect>
          </ElFormItem>
        </ElForm>
      </ElDialog>
    )
  }
})
